class_name ParticlePoisonBullet
extends MagicBulletBase


@export var speed: float = 200
var dir: Vector2 = Vector2.RIGHT

@export var life_time: float = 0.5
var life_timer: float = 0

var is_destroy: bool = false
@onready var particle_poison_bullet: GPUParticles2D = $ParticlePoisonBullet

@onready var audio_explosion: AudioStreamPlayer2D = $AudioExplosion
@onready var audio_burning: AudioStreamPlayer2D = $AudioBurning


func _ready() -> void:
	audio_burning.play()


func _physics_process(delta: float) -> void:
	process_move(delta)
	process_destroy(delta)
	if not is_destroy:
		process_hit()
	

func process_destroy(delta: float):
	if is_destroy: return
	
	life_timer += delta
	if life_timer >= life_time:
		is_destroy = true
		particle_poison_bullet.emitting = false
		audio_burning.stop()
		await get_tree().create_timer(1.0).timeout
		queue_free()
	

func process_move(delta: float):
	#if is_destroy: return
	
	position += dir * speed * delta
	
			
func _on_hit_area_body_entered(body: Node2D) -> void:
	var level = get_tree().current_scene as Level
	level.emit_particle("particle_poison_bullet_hit_effect", global_position)
	level.camera.start_shake(hit_cam_shake_strength, hit_cam_shake_duration)
	audio_burning.stop()
	audio_explosion.play()
	
	dir = Vector2.ZERO
	is_destroy = true
	particle_poison_bullet.emitting = false
	await get_tree().create_timer(1.0).timeout
	queue_free()
	

func on_hit(source: Node2D):
	_on_hit_area_body_entered(self)
	if source is UnitBase:
		add_poison_buff_to_target(source)


func add_poison_buff_to_target(source: Node2D):
	var unit = source as UnitBase
	
	var poison_hit_rate = poison_hit_rate 
	var is_hit = randf() < poison_hit_rate
	if is_hit and not unit.get_buff_by_name("buff_poison"):
		var buff_inst = unit.add_buff("buff_poison", sender)
		
		buff_inst.duration = poison_debuff_duration
		buff_inst.damage_per_second = poison_damage_per_second
		buff_inst.sender = sender
		buff_inst.start_buff()
	
